from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required

def login_view(request):
    # 如果用户已经登录，直接重定向到主页
    if request.user.is_authenticated:
        return redirect('/')
    
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        remember_password = request.POST.get('remember_password')
        
        user = authenticate(request, username=username, password=password)
        
        if user is not None:
            login(request, user)
            # 获取登录后要跳转的页面
            next_page = request.GET.get('next', '/')
            return redirect(next_page)
        else:
            return render(request, 'accounts/login.html', {
                'error_message': '用户名或密码错误'
            })
    
    return render(request, 'accounts/login.html')

@login_required
def logout_view(request):
    logout(request)
    return redirect('accounts:login')
